package com.joint.web.action.manage;

import com.fz.us.base.bean.BaseEnum;
import com.fz.us.base.bean.Pager;
import com.fz.us.base.util.LogUtil;
import com.fz.us.dict.bean.DictBean;
import com.fz.us.dict.entity.Dict;
import com.fz.us.dict.service.DictService;
import com.google.common.collect.Lists;
import com.joint.base.bean.FlowEnum;
import com.joint.base.entity.*;
import com.joint.base.exception.users.DutyNotExistsException;
import com.joint.base.exception.workflow.PcfgNotExistException;
import com.joint.base.service.DepartmentService;
import com.joint.base.service.UsersService;
import com.joint.base.util.DataUtil;
import com.joint.core.entity.manage.Seal;
import com.joint.core.service.SealService;
import com.joint.web.action.BaseFlowAction;
import net.sf.json.JSONObject;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.ParentPackage;

import javax.annotation.Resource;
import java.util.*;

/**
 * Created by ZhuChunXiao on 2017/3/20.
 */
@ParentPackage("manage")
public class AjaxSealAction extends BaseFlowAction {
    @Resource
    private SealService sealService;
    @Resource
    private DictService dictService;
    @Resource
    private UsersService usersService;

    /**
     * 使用类型 1内用，2外借
     */
    private String type;
    /**
     * 使用类型（读）
     */
    private String typeText;
    /**
     * 归还日期
     */
    private String returnDate;
    /**
     *印章名称
     */
    private String sealNameId;
    /**
     * 盖章事由
     */
    private String reason;
    /**
     * 盖章内容/份数
     */
    private String content;
    /**
     * 附件（读）
     */
    private String fileId;
    /**
     * 附件（传）
     */
    private String fileIds;
    /**
     * 是否已归还
     */
    private boolean giveBack;
    /**
     * 印章名称
     */
    private List<Map<String, Object>> nameDict;

    private Seal seal;
    private int reportCenter;
    private int ifCentralStaff;
    private int numStatus;

    private String step;
    private Users loginUser;
    public String execute(){
        return "seal";
    }

    public String list(){
        pager = new Pager(0);
        /*
        if (rows <= 0){
            rows = 10;
        }
        pager.setPageSize(rows);
        pager.setPageNumber(page);*/
        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.desc);
        if(StringUtils.isNotEmpty(sidx)&& BaseEnum.OrderType.valueOf(sord)!=null){
            pager.setOrderBy(sidx);
            pager.setOrderType(BaseEnum.OrderType.valueOf(sord));
        }
        Company com = usersService.getCompanyByUser();
        Users user = usersService.getLoginInfo();
        Map<String,Object> params = new HashMap<String,Object>();
      //  params = getSearchFilterParams(_search,params,filters);
        params.put("company",com);
        params.put("state",BaseEnum.StateEnum.Enable);

        if(StringUtils.isNotEmpty(step)){
            if(step.equals("1")){
                //申请中
                params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed, FlowEnum.ProcessState.Deny});
                params.put("step", "1");
                pager=sealService.findByPagerAndLimit(false, "seal", pager, params);
            }else if(step.equals("2")){
                //外借未归还
                params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Finished});
                params.put("step", "2");
                params.put("type", "2");
                pager=sealService.findByPagerAndFinish("seal", pager, params);
            }else if(step.equals("3")){
                //已归还
                params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Finished});
                params.put("step", "3");
                pager=sealService.findByPagerAndLimit(false, "seal", pager, params);
            }
        }else{
            //所有单子
            params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed, FlowEnum.ProcessState.Finished, FlowEnum.ProcessState.Deny});
            pager=sealService.findByPagerAndLimit(true, "seal", pager, params);
        }

        List<Seal> sealList;
        if (pager.getTotalCount() > 0){
            sealList = (List<Seal>) pager.getList();
        }else{
            sealList= new ArrayList<>();
        }
        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;

        for(Seal seal: sealList){
            rMap = new HashMap<String, Object>();
            rMap.put("id",seal.getId());
            if(seal.getType().equals("1")){
                rMap.put("type","内用");
            }else if(seal.getType().equals("2")){
                rMap.put("type","外借");
            }else{
                rMap.put("type","未知");
            }
            if(seal.isGiveBack()){
                rMap.put("giveBack","已还");
            }else{
                rMap.put("giveBack","未还");
            }
            rMap.put("name",seal.getSealName() != null?seal.getSealName().getName():"");
            rMap.put("creater", seal.getCreater() != null ? seal.getCreater().getName() : "");
            rMap.put("createDate", DataUtil.DateToString(seal.getCreateDate(),"yyyy-MM-dd"));
            rMap.put("state",seal.getProcessState().value());
            JSONObject o = JSONObject.fromObject(rMap);
            dataRows.add(o);
        }
        data.put("dataRows",dataRows);
        data.put("page",page);
        data.put("rows",rows);
        long recordsNum = pager.getTotalCount();
        data.put("total",calcPageNum(recordsNum));
        data.put("records", recordsNum);
        return  ajaxJson(JSONObject.fromObject(data).toString());
    }

    public String input(){
        Company company = usersService.getCompanyByUser();
        List<Dict> sealName = dictService.listFormDefinedEnable(DictBean.DictEnum.SealName, usersService.getCompanyByUser().getId());
        Map<String,Object> rMap = null;
        nameDict = new ArrayList<Map<String, Object>>();
        if (StringUtils.isNotEmpty(keyId)){
            fileId ="";
            seal = sealService.get(keyId);
            if(seal.getFile() != null && seal.getFile().size()>0){
                for(FileManage f:seal.getFile()){
                    fileId+=f.getId()+",";
                }
            }
            for(Dict name:sealName){
                rMap = new HashMap<String, Object>();
                rMap.put("id",name.getId());
                rMap.put("name",name.getName());
                rMap.put("selected","");
                if(seal.getSealName()!=null && StringUtils.equals(name.getId(), seal.getSealName().getId())){
                    rMap.put("selected","selected");
                }
                nameDict.add(rMap);
            }
        } else {
            for(Dict name:sealName){
                rMap = new HashMap<String, Object>();
                rMap.put("id",name.getId());
                rMap.put("name",name.getName());
                rMap.put("selected","");
                nameDict.add(rMap);
            }
        }
        return "input";
    }

    public String read(){
        loginUser = usersService.getLoginInfo();
        if(StringUtils.isNotEmpty(keyId)){
            numStatus = workflowService.getNumStatus(keyId, loginUser);
            flowNumStatus = workflowService.getFlowNumStatus(keyId);
            seal=sealService.get(keyId);
            fileId="";
            typeText="";
            if(seal.getFile() != null && seal.getFile().size()>0){
                for(FileManage f:seal.getFile()){
                    fileId+=f.getId()+",";
                }
            }
            if(seal.getType().equals("1")){
                typeText="内用";
            }else if(seal.getType().equals("2")){
                typeText="外借";
            }else{
                typeText="未知";
            }
        }
        return "read";
    }

    public void setData(){
        if(StringUtils.isNotEmpty(keyId)){
            seal=sealService.get(keyId);
        }else{
            seal=new Seal();
            seal.setCreater(usersService.getLoginInfo());
        }
        seal.setType(type);
        seal.setReturnDate(DataUtil.StringToDate(returnDate));
        seal.setSealName(dictService.get(sealNameId));
        seal.setReason(reason);
        seal.setContent(content);
        seal.setStep("1");
        seal.setReportCenter(reportCenter == 1);
        List<FileManage> fileList = Lists.newArrayList();
        if(StringUtils.isNotEmpty(fileIds)){
            for(String f:fileIds.split(",")){
                fileList.add(fileManageService.get(f.trim()));
            }
        }
        seal.setFile(fileList);
        seal.setCompany(usersService.getLoginInfo().getCompany());
    }

    public String save(){
        setData();
        try {
            if(StringUtils.isNotEmpty(keyId)){
                sealService.update(seal);
            } else {
                Map<String, Object> various = new HashMap<String, Object>();
                various.put("numStatus", 0);
                various.put("curDutyId", curDutyId);
                various.put("initDuty", curDutyId);
                sealService.save(seal, "seal", various);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }

        return ajaxHtmlCallback("200", "保存成功！", "操作状态");
    }

    // 提交
    public String commit(){
        setData();
        Map<String, Object> var1 = new HashMap<String, Object>();
        var1.put("numStatus", 0);
        var1.put("curDutyId", curDutyId);
        var1.put("initDuty", curDutyId);
        Map<String, Object> var2 = new HashMap<String, Object>();
        var2.put("numStatus", 1);
        var2.put("curDutyId", curDutyId);

        List<Users> sealusers=Lists.newArrayList();
        List<String> sealadminList=Lists.newArrayList();
        Set<Duty> dutySet=usersService.getLoginInfo().getDutySet();
        for(Duty duty:dutySet){
            Department dept=duty.getDepartment().getParent()==null?duty.getDepartment():duty.getDepartment().getParent();
            Set<Department> deptSet=dept.getChildren();
            for(Department cdept:deptSet){
                    Set<Power> powers = cdept.getPowerSet();
                    for(Power power:powers){
                        if(power.getPost().getName().equals("印章管理员")){
                            List<Users> usersList=dutyService.getPersons(cdept,power.getPost());
                            for(Users user:usersList){
                                sealadminList.add(user.getId().trim());
                                sealusers.add(user);
                            }
                        }
                    }

            }
        }
        var2.put("sealadmin", sealadminList);
        var1.put("sealadmin", sealadminList);
        seal.setSealAdmin(sealusers);

        try {
            if (StringUtils.isNotEmpty(keyId)) {
                sealService.approve(seal, FlowEnum.ProcessState.Running, var2, curDutyId,comment);
            } else {
                keyId = sealService.commit(seal, "seal", var1, var2, curDutyId);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }

        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    //审批1
    public String approve1(){
        ifCentralStaff=0;
        seal = sealService.get(keyId);
        Map<String, Object> var1 = new HashMap<String, Object>();
        var1.put("curDutyId", curDutyId);

        Set<Duty> dutySet = usersService.getLoginInfo().getDutySet();
        for (Duty duty:dutySet){
            if(duty.getDepartment().getParent()!=null){
                LogUtil.info("ceshi"+duty.getDepartment().getParent().getName());
                if(StringUtils.equals(duty.getDepartment().getParent().getName(),"产业中心")){
                    ifCentralStaff=1;
                    break;
                }
            }
        }
        if(ifCentralStaff==1){
            var1.put("numStatus",3);
        }else{
            var1.put("numStatus",2);
        }
        var1.put("curDutyId", curDutyId);
        var1.put("ifCentralStaff", ifCentralStaff);

        if(StringUtils.isEmpty(comment)){
            comment="";
        }
        try {
            if (StringUtils.isNotEmpty(keyId)) {
                sealService.approve(seal, FlowEnum.ProcessState.Running, var1, curDutyId, comment);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        } catch (Exception e){
            return ajaxHtmlCallback("404", "操作异常，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    //审批2
    public String approve2(){
        seal = sealService.get(keyId);
        Map<String, Object> var1 = new HashMap<String, Object>();
        var1.put("curDutyId", curDutyId);

        if(reportCenter==1){
            var1.put("numStatus",4);
        }else{
            var1.put("numStatus",3);
        }
        var1.put("curDutyId", curDutyId);
        var1.put("reportCenter", reportCenter);
        seal.setReportCenter(reportCenter == 1 ? true : false);
        sealService.update(seal);

        if(StringUtils.isEmpty(comment)){
            comment="";
        }
        try {
            if (StringUtils.isNotEmpty(keyId)) {
                sealService.approve(seal, FlowEnum.ProcessState.Running, var1, curDutyId, comment);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        } catch (Exception e){
            return ajaxHtmlCallback("404", "操作异常，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    //审批3
    public String approve3(){
        seal = sealService.get(keyId);
        Map<String, Object> var1 = new HashMap<String, Object>();
        var1.put("curDutyId", curDutyId);
        var1.put("numStatus", 4);
        if(StringUtils.isEmpty(comment)){
            comment="";
        }
        try {
            if (StringUtils.isNotEmpty(keyId)) {
                sealService.approve(seal, FlowEnum.ProcessState.Running, var1, curDutyId, comment);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        } catch (Exception e){
            return ajaxHtmlCallback("404", "操作异常，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    //审批4
    public String approve4(){
        seal = sealService.get(keyId);
        Map<String, Object> var1 = new HashMap<String, Object>();
        var1.put("curDutyId", curDutyId);
        var1.put("numStatus",5);

        seal.setStep("2");
        sealService.update(seal);

        if(StringUtils.isEmpty(comment)){
            comment="";
        }
        try {
            if (StringUtils.isNotEmpty(keyId)) {
                sealService.approve(seal, FlowEnum.ProcessState.Finished, var1, curDutyId, comment);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        } catch (Exception e){
            return ajaxHtmlCallback("404", "操作异常，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    /**
     * 退回
     * @return
     */
    public String reject() {
        if (StringUtils.isNotEmpty(keyId)) {
            seal = sealService.get(keyId);
            List<ActivityImpl> activityList= workflowService.findAllActivitiesByKey("seal");
            String key=activityList.get(0).getId();
            System.out.println("Activity key:"+key);
            LogUtil.info("numStatus:"+numStatus);
            if(StringUtils.isEmpty(comment)) comment="";
            sealService.reject(seal, key, numStatus, comment, curDutyId);
        }

        return ajaxHtmlCallback("200", "退回成功！", "操作状态");
    }

    /**
     * 否决
     * @return
     */
    public String deny() {
        if (StringUtils.isNotEmpty(keyId)) {
            seal = sealService.get(keyId);
            List<ActivityImpl> activityList= workflowService.findAllActivitiesByKey("seal");
            String key= activityList.get(activityList.size()-1).getId();
            if(StringUtils.isEmpty(comment)){
                comment="";
            }
            sealService.deny(seal, key, comment, curDutyId);
        }
        return ajaxHtmlCallback("200", "否决成功！", "操作状态");
    }

    /**
     * 确认归还
     * @return
     */
    public String giveBack(){
        boolean isChange=false;
        if(StringUtils.isNotEmpty(keyId)){
            seal=sealService.get(keyId);
            List<Users> usersList=seal.getSealAdmin();
            for(Users user:usersList){
                if(user.getId().equals(usersService.getLoginInfo().getId())){//判断当前登录的人和被选择的条目是否有关系
                    isChange=true;
                    break;
                }
            }
            if(isChange){
                seal.setStep("3");
                seal.setGiveBack(true);
                seal.setReturnDate(DataUtil.StringToDate(returnDate));
                sealService.update(seal);
            }else{
                return ajaxHtmlCallback("400", "没有权限！", "操作状态");
            }
        }
        return ajaxHtmlCallback("200", "归还成功！", "操作状态");
    }

    public void ceshi(){
        Set<Duty> dutySet=usersService.getLoginInfo().getDutySet();
        for(Duty duty:dutySet){
            Department dept=duty.getDepartment().getParent()==null?duty.getDepartment():duty.getDepartment().getParent();
            Set<Department> deptSet=dept.getChildren();
            for(Department cdept:deptSet){
                Set<Power> powers = cdept.getPowerSet();
                for(Power power:powers){
                    if(power.getPost().getName().equals("印章管理员")){
                        List<Users> usersList=dutyService.getPersons(cdept,power.getPost());
                        for(Users user:usersList){
                            System.out.println("####"+user.getName());
                        }
                    }
                }

            }
        }
    }



    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getReturnDate() {
        return returnDate;
    }

    public void setReturnDate(String returnDate) {
        this.returnDate = returnDate;
    }

    public String getSealNameId() {
        return sealNameId;
    }

    public void setSealNameId(String sealNameId) {
        this.sealNameId = sealNameId;
    }

    public String getReason() {
        return reason;
    }

    public void setReason(String reason) {
        this.reason = reason;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getFileId() {
        return fileId;
    }

    public void setFileId(String fileId) {
        this.fileId = fileId;
    }

    public String getFileIds() {
        return fileIds;
    }

    public void setFileIds(String fileIds) {
        this.fileIds = fileIds;
    }

    public boolean isGiveBack() {
        return giveBack;
    }

    public void setGiveBack(boolean giveBack) {
        this.giveBack = giveBack;
    }

    public Seal getSeal() {
        return seal;
    }

    public void setSeal(Seal seal) {
        this.seal = seal;
    }

    public int getReportCenter() {
        return reportCenter;
    }

    public void setReportCenter(int reportCenter) {
        this.reportCenter = reportCenter;
    }

    public int getIfCentralStaff() {
        return ifCentralStaff;
    }

    public void setIfCentralStaff(int ifCentralStaff) {
        this.ifCentralStaff = ifCentralStaff;
    }

    @Override
    public int getNumStatus() {
        return numStatus;
    }

    @Override
    public void setNumStatus(int numStatus) {
        this.numStatus = numStatus;
    }

    public Users getLoginUser() {
        return loginUser;
    }

    public void setLoginUser(Users loginUser) {
        this.loginUser = loginUser;
    }

    public String getStep() {
        return step;
    }

    public void setStep(String step) {
        this.step = step;
    }

    public List<Map<String, Object>> getNameDict() {
        return nameDict;
    }

    public void setNameDict(List<Map<String, Object>> nameDict) {
        this.nameDict = nameDict;
    }

    public String getTypeText() {
        return typeText;
    }

    public void setTypeText(String typeText) {
        this.typeText = typeText;
    }
}
